package com.mb.mp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mb.common.utils.OSSUtil;
import com.mb.mp.service.IFileUploadService;
import com.mb.mp.util.WaterMarkUtils;
import com.mb.common.config.CommonConfig;
import com.mb.common.utils.DateUtils;
import com.mb.common.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * 文件上传实现
 *
 * @author
 * @create 2018-03-27 下午6:41
 **/
@Service("fileUploadService")
@Slf4j
public class FileUploadServiceImpl implements IFileUploadService {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);

    @Autowired
    private CommonConfig commonConfig;

    @Override
    public JSONObject fileUpload(JSONObject reqData) {
        JSONObject resData = new JSONObject();
        resData.put("code",0);
        resData.put("msg","成功");

        String base64Str = reqData.getString("base64Str");
        String fileType = reqData.getString("fileType");
        String imgType =fileType.substring(1);
        imgType = "image/" + imgType;
        String targetPath = "";

        try {
            String dateStr = DateUtils.format(new Date(),"yyyyMMdd");
            File filePath = new File(commonConfig.getImgRootPath() + "upload/" + dateStr);
            if(!filePath.exists()){
                filePath.mkdirs();
            }

            String fileName = RandomStringUtils.randomAlphabetic(16) + fileType;
            targetPath = commonConfig.getImgRootPath() + "upload/" + dateStr + "/" + fileName;
            logger.info("targetPath :"+targetPath);
            //生成图片
            this.generateImage(base64Str,targetPath);

            //压缩
            try{
                Thumbnails.of(targetPath)
                        .scale(1f)
                        .outputQuality(0.3f)
                        .toFile(targetPath);
            }catch (Exception e) {
                logger.error("fileUpload Exception",e);
            }
            File file = new File(targetPath);
            String key = "upload/" + dateStr + "/" + fileName;
            String outPath = OSSUtil.uploadImg(key, FileUtils.readFileToByteArray(file),imgType);
            // 截取
            outPath = outPath.substring(0, outPath.indexOf("?"));
            outPath = outPath.replaceAll(commonConfig.getOssDomain(),commonConfig.getImgDomain());
            logger.info("outPath:",outPath);
            JSONObject data = new JSONObject();
            data.put("imgPath",outPath);
            resData.put("data",data);
        } catch (Exception e) {
            logger.error("fileUpload Exception",e);
        }finally {

        }
        return resData;
    }


    @Override
    public JSONObject fileUploadByMult(MultipartFile file, JSONObject reqData) {
        JSONObject resData = new JSONObject();
        resData.put("code",0);
        resData.put("msg","成功");

        String targetPath = "";
        try {
            String systemName = reqData.getString("systemName");
            String dateStr = DateUtils.format(new Date(),"yyyyMMdd");
            File filePath = new File(commonConfig.getImgRootPath() + "upload/" + dateStr);
            if(!filePath.exists()){
                filePath.mkdirs();
            }

            String origFileName = file.getOriginalFilename();
            logger.info("origFileName :" + origFileName);
            logger.info("origFileName fileSize:" + file.getSize());
            String suffix = WaterMarkUtils.getSuffix(origFileName);
            logger.info("origFileName suffix:" + suffix);

            String fileType = "." + suffix;
            String fileName = RandomStringUtils.randomAlphabetic(16) + fileType;
            logger.info("origFileName fileName:" + fileName);
            logger.info("origFileName fullPath:" + filePath.getAbsolutePath() + "/" + fileName);
            FileUtil.uploadFile(file.getBytes(), filePath.getAbsolutePath() + "/", fileName);

            // oss上传
            targetPath = commonConfig.getImgRootPath() + "upload/" + dateStr + "/" + fileName;
            File file1 = new File(targetPath);
            String key = "upload/" + dateStr + "/" + fileName;
            String outPath = OSSUtil.uploadVideoOSS(key, FileUtils.readFileToByteArray(file1),fileName);
            // 截取
            outPath = outPath.substring(0, outPath.indexOf("?"));
            outPath = outPath.replaceAll(commonConfig.getOssDomain(),"");
            outPath = commonConfig.getImgDomain() + outPath;
            log.info("outPath :" + outPath);
            JSONObject data = new JSONObject();
            data.put("imgPath",outPath);
            resData.put("data",data);
        } catch (Exception e) {
            logger.error("fileUploadByMult Exception",e);
        }
        return resData;
    }

    /**
     * 生成图片
     *
     * @param imgStr
     * @param targetPath
     * @return
     */
    public  boolean generateImage(String imgStr,String targetPath ) {
        if (imgStr == null) // 图像数据为空
            return false;

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(targetPath);
            // Base64解码
            byte[] b = Base64.decodeBase64(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }

            out.write(b);
            out.flush();
            return true;
        } catch (Exception e) {
            try {
                out.close();
            } catch (IOException e1) {
                logger.error("generateImage close IOException",e);
            }
            return false;
        }
    }


}
